package com.sunny.custom.spring.servlet.framework.v2;

import com.sunny.custom.spring.servlet.framework.anno.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Sunny
 * @date 2020/1/17
 */
public class CustomDispatcherServlet extends HttpServlet {

    //保存配置文件中的属性
    private Properties prop = new Properties();

    //保存扫描到的className
    private List<String> classNames = new ArrayList<String>();

    //IOC容器
    private Map<String, Object> ioc = new ConcurrentHashMap<String, Object>();

    //保存url与method的对应关系
    private Map<String, Method> handlerMapping = new ConcurrentHashMap<String, Method>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //6、运行阶段
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception ! \n" + Arrays.toString(e.getStackTrace()));
        }
    }

    /**
     * 执行调用
     *
     * @param req  请求
     * @param resp 响应
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();

        uri = uri.replace(contextPath, "").replaceAll("/+", "/");

        if (!handlerMapping.containsKey(uri)) {
            resp.getWriter().write("404 Not Found!!");
            return;
        }

        Method method = handlerMapping.get(uri);
        Map<String, String[]> map = req.getParameterMap();

        //获取方法的形参列表
        Class<?>[] parameterTypes = method.getParameterTypes();

        //保存赋值参数的位置
        Object[] paramValues = new Object[parameterTypes.length];

        //根据参数位置动态赋值
        for (int i = 0, e = parameterTypes.length; i < e; i++) {
            Class<?> parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class) {
                paramValues[i] = req;
            } else if (parameterType == HttpServletResponse.class) {
                paramValues[i] = resp;
            } else if (parameterType == String.class) {
                //提取方法中加了注解的参数
                Annotation[][] pa = method.getParameterAnnotations();
                for (int j = 0, k = pa.length; j < k; j++) {
                    for (Annotation annotation : pa[j]) {
                        if (annotation instanceof CustomRequestParam) {
                            String paramName = ((CustomRequestParam) annotation).value();

                            if (!"".equals(paramName.trim())) {
                                String value = Arrays.toString(map.get(paramName)).replaceAll("\\[|\\]", "")
                                        .replaceAll("\\s", ",");
                                paramValues[i] = value;
                            }
                        }
                    }
                }
            }
        }

        //通过反射拿到method所在类的class，再去容器中取对象
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(ioc.get(beanName), paramValues);

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            //1、加载配置文件
            doLoadConfig(config.getInitParameter("contextConfigLocation"));

            //2、扫描相关类
            doScanner(prop.getProperty("scanPackage"));

            //3、初始化类，并存入IOC容器
            doInstance();

            //4、完成DI依赖注入
            doAutowired();

            //5、初始化handlerMapping
            initHandlerMapping();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("custom servlet is success！");
    }

    /**
     * 映射uri与method
     *
     * @author sunny
     * @date 2020/1/17
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (clazz.isAnnotationPresent(CustomController.class)) {

                String baseUri = "";

                if (clazz.isAnnotationPresent(CustomRequestMapping.class)) {
                    CustomRequestMapping requestMapping = clazz.getAnnotation(CustomRequestMapping.class);
                    baseUri = requestMapping.value().trim();
                }

                for (Method method : clazz.getMethods()) {
                    if (method.isAnnotationPresent(CustomRequestMapping.class)) {
                        CustomRequestMapping requestMapping = method.getAnnotation(CustomRequestMapping.class);

                        //确保路径只会有一个 /
                        String uri = ("/" + baseUri + "/" + requestMapping.value().trim()).replaceAll("/+", "/");
                        handlerMapping.put(uri, method);

                        System.out.println("Mapped: " + uri + ". " + method);
                    }
                }
            }
        }
    }

    /**
     * 依赖注入
     *
     * @author sunny
     * @date 2020/1/17
     */
    private void doAutowired() throws ClassNotFoundException, IllegalAccessException {
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(CustomAutowired.class)) {
                    CustomAutowired autowired = field.getAnnotation(CustomAutowired.class);
                    String fieldName = autowired.value();

                    if ("".equals(fieldName)) {
                        fieldName = field.getType().getName();
                    }

                    field.setAccessible(true);

                    field.set(entry.getValue(), ioc.get(fieldName));
                }
            }
        }
    }

    /**
     * 初始化被标识的类
     *
     * @throws Exception
     */
    private void doInstance() throws Exception {
        if (classNames.isEmpty()) {
            return;
        }

        //初始化相关类
        for (String className : classNames) {
            Class<?> clazz = Class.forName(className);

            if (clazz.isAnnotationPresent(CustomController.class)) {
                Object instance = clazz.newInstance();

                String beanName = toLowerFirstCase(clazz.getSimpleName());
                ioc.put(beanName, instance);
            } else if (clazz.isAnnotationPresent(CustomService.class)) {
                //1、根据自定义的类名存入容易
                CustomService service = clazz.getAnnotation(CustomService.class);
                String beanName = service.value();

                //2、默认类名首字母小写传入
                if ("".equals(beanName)) {
                    beanName = toLowerFirstCase(clazz.getSimpleName());
                }

                Object instance = clazz.newInstance();
                ioc.put(beanName, instance);

                //3、根据类型存入
                for (Class<?> clazzInterface : clazz.getInterfaces()) {
                    if (ioc.containsKey(clazzInterface.getName())) {
                        throw new Exception("The " + clazzInterface.getName() + " is exists!");
                    }
                    ioc.put(clazzInterface.getName(), instance);
                }

            }
        }
    }

    /**
     * 首字母转小写
     *
     * @param simpleName beanName
     * @author sunny
     * @date 2020/1/17
     */
    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        //通过对字母的ASCII码进行数算，将字母转换为大写，大写字母的 ASCII 码要小于小写字母的 ASCII 码
        chars[0] += 32;
        return String.valueOf(chars);
    }

    /**
     * 加载配置文件
     *
     * @param contextConfigLocation application文件名
     * @throws IOException
     */
    private void doLoadConfig(String contextConfigLocation) throws IOException {
        //从类路径下找到spring配置文件的地址
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        prop.load(is);
    }

    /**
     * 扫描classpath下的class文件
     *
     * @param scanPackage 扫描的包路径
     * @author sunny
     * @date 2020/1/17
     */
    private void doScanner(String scanPackage) {
        //将包路径替换为文件路径
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classFile = new File(url.getFile());

        //保存所有class文件全限定名
        for (File file : classFile.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                if (file.getName().endsWith(".class")) {
                    String className = scanPackage + "." + file.getName().replace(".class", "");
                    classNames.add(className);
                }
            }
        }
    }
}
